package com.situ.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.mall.constant.RedisConstants;
import com.situ.mall.mapper.ProductMapper;
import com.situ.mall.pojo.Product;
import com.situ.mall.pojo.query.ProductQuery;
import com.situ.mall.service.IProductService;
import com.situ.mall.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Cacheable(value = "product",key="#root.methodName+':' + #productQuery",sync = true)
    @Override
    public PageResult<Product> list(ProductQuery productQuery) {
        PageHelper.startPage(productQuery.getPage(),productQuery.getLimit());
        List<Product> list = productMapper.list(productQuery);
        PageInfo pageInfo = new PageInfo(list);
        int count = (int)pageInfo.getTotal();
        return new PageResult<>(0,"",count,list);
    }

    @Override
    public void deleteById(Integer id) {
        productMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        productMapper.deleteAll(ids);
    }

    @Override
    public void add(Product product) {
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, product.getMainImage());
        productMapper.insertSelective(product);
    }
    @Cacheable(value = "product",key = "#root.methodName+':' + #id")
    @Override
    public Product selectById(Integer id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @CacheEvict(value = "product",key = "'selectById:'+#product.id")
    @Override
    public void update(Product product) {
        productMapper.updateByPrimaryKeySelective(product);
    }
}
